#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import time
from datetime import date
import os
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders


mailServer="smtp.gmail.com:587"
mailFrom= mailBoxUser = "server@roboma.cz"
mailTo = "petr.jakes.tpc@gmail.com"
mailBoxPassword = "RoboServer"
mailSubjectMountError = "Atlant server - chyba zálohování"

def newSendMail(server=mailServer, 
                sender=mailFrom, 
                to=[mailTo], 
                subject=mailSubjectMountError, 
                text='', 
                user = mailBoxUser, 
                password = mailBoxPassword, 
                files=[]):
    assert type(to)==list
    assert type(files)==list
    fro = sender

    msg = MIMEMultipart()
    msg['From'] = fro
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )
    if len(files):
        for file in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(file,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'
                           % os.path.basename(file))
            msg.attach(part)
    try:
        smtp = smtplib.SMTP(server)    
        if user or password: # je mozna i autentifikace
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            smtp.login(user, password) 
        print smtp.sendmail(fro, to, msg.as_string() )
        smtp.quit()
        smtp.close()
        
    except Exception, why:
        # vytiskneme na konzoli a ignorujeme ...
        print Exception
        print "SMTP SEND chyba:",why

if __name__ == '__main__':

        text = "zkouška mailu"
        print text
        newSendMail(text= text)
